package com.example.demo.algorithm.test;

import com.example.demo.algorithm.linear.Stack;

/**
 * @Author: xiatian
 * @CreateTime: 2021/9/18 4:30 下午
 * @Description: 通过栈来实现逆波兰表达式
 */
public class ReversePolishNotation {
    public static void main(String[] args) {
        //中缀表达式3*(17-15)+18/6的逆波兰表达式如下
        String[] notation = {"3", "17", "15", "-", "*", "18", "6", "/", "+"};
        int result = caculate(notation);
        System.out.println("逆波兰表达式的结果为:" + result);
    }

    public static int caculate(String[] notation) {
        Stack<Integer> stack = new Stack<Integer>();
        Integer o1;
        Integer o2;
        Integer result = null;
        for (int i = 0; i < notation.length; i++) {
            String op = notation[i];
            switch (op) {
                case "+":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    result = o2 + o1;
                    stack.push(result);
                    break;
                case "-":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    result = o2 - o1;
                    stack.push(result);
                    break;
                case "*":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    result = o2 * o1;
                    stack.push(result);
                    break;
                case "/":
                    o1 = stack.pop();
                    o2 = stack.pop();
                    result = o2 / o1;
                    stack.push(result);
                    break;
                default:
                    stack.push(Integer.parseInt(op));
                    break;
            }

        }
        Integer res = stack.pop();
        return res;
    }

}
